package com.yes_iot.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


public class FileUtil {
    public static FileInfo setPath(FileInfo fileInfo,String basePath,String mappingPath,String domain) {
        SimpleDateFormat dfYMD = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat dfH = new SimpleDateFormat("HH");
        Date now = new Date();
        Long fileDirName = System.currentTimeMillis();
        String fileType = fileInfo.getName().substring(fileInfo.getName().lastIndexOf("."));
        String pathDir = dfYMD.format(now) + File.separator + dfH.format(now) + File.separator + fileDirName
                + File.separator;
        String subPath = pathDir + fileDirName + fileType;
        fileInfo.setPathDir(basePath + File.separator + pathDir);
        fileInfo.setPath(basePath + File.separator + subPath);
        fileInfo.setUrl(domain + mappingPath + subPath.replaceAll("\\\\", "\\/")); //防止在window下url出现\\
        // 本地保存文件
        return fileInfo;
    }
    public static String saveFile(MultipartFile file, String path) {
        try {
            File targetFile = new File(path);
            if (targetFile.exists()) {
                return path;
            }
            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs();
            }
            file.transferTo(targetFile);
            return path;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static FileInfo getFileInfo(MultipartFile file) throws Exception {

        FileInfo fileInfo = new FileInfo();
        fileInfo.setFileId(UUID.randomUUID().toString());// 将文件的md5设置为文件表的id
        fileInfo.setName(file.getOriginalFilename());
        fileInfo.setContentType(file.getContentType());
        fileInfo.setIsImg(fileInfo.getContentType().startsWith("image/"));
        fileInfo.setSize(file.getSize());
        fileInfo.setCreateTime(new Date());

        return fileInfo;
    }

    public static boolean deleteFile(String pathname) {
        File file = new File(pathname);
        if (file.exists()) {
            boolean flag = file.delete();
            if (flag) {
                File[] files = file.getParentFile().listFiles();
                if (files == null || files.length == 0) {
                    file.getParentFile().delete();
                }
            }
            return flag;
        }
        return false;
    }
}
